package top.swimmer.tools.data.binary;

public class BinarySearch {
    public static int binarySearch(int[] arr, int target) {
        int start = 0;
        int end = arr.length;
        while (start <= end) {
            int index = start + (end - start) / 2;
            int middle = arr[index];
            if (middle == target) {
                return index;
            } else if (middle > target) {
                end = index - 1;
            } else {
                start = index + 1;
            }
        }
        return -1;
    }

    public static int binarySearchLowerBound(int[] arr, int target) {
        int start = 0;
        int end = arr.length;
        while (start < end) {
            int index = start + (end - start) / 2;
            int middle = arr[index];
            if (middle < target) {
                start = index + 1;
            } else {
                end = index;
            }
        }
        if (end < arr.length && arr[end] == target) {
            return end;
        }
        return -1;
    }

    public static int other(int[] A, int target) {
        int low = 0, high = A.length, mid;
        while(low <= high){
            mid = low + (high - low) / 2;
            if(target <= A[mid]){
                high = mid - 1;
            }else{
                low = mid + 1;
            }
        }
        if(low < A.length && A[low] == target)
            return low;
        else
            return -1;
    }

    public static void main(String[] args) {
        System.out.println(binarySearch(new int[]{1,1,1,2,2,2,5,5,7,9,13,25,78,98}, 5));
        System.out.println(binarySearchLowerBound(new int[]{1,1,1,2,2,2,5,5,7,9,13,25,78,98}, 5));
        System.out.println(other(new int[]{1,1,1,2,2,2,5,5,7,9,13,25,78,98}, 2));
    }
}
